package com.chungbv.dbhelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.chungvb.utility.XMLGetData;
import com.karaokevietnam7so.R;

@SuppressLint("SdCardPath")
public class DataBaseHelper extends SQLiteOpenHelper
{
	private static String TAG = "DataBaseHelper"; 
	private static String DB_PATH = "";
	private static String DB_NAME = "karaoke";// Database name
	private SQLiteDatabase mDataBase;
	private final Context mContext;

	public DataBaseHelper(Context context)
	{
		super(context, DB_NAME, null, 1);// 1? its Database Version
		DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
		this.mContext = context;

	}

	public boolean comparePackageVersion()
	{
		int oldVersion;
		int newVersion;
		
		final XMLGetData xml = new XMLGetData(mContext, "config.xml");
		xml.getNodeList();

		oldVersion = Integer.parseInt(xml.getData(0, "version"));

		try {
			newVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
		}
		catch (NameNotFoundException nnfe) {
			newVersion = 999;
		}

		// Compare
		if (oldVersion < newVersion) {
			// Write new XML file to memory
			xml.setData(0, "version", newVersion);
			
			// Allow create new database
			return true;
		}

		return false;
	}

	public void createDataBase() throws IOException
	{
		// If database not exists copy it from the assets
		boolean mDataBaseExist = checkDataBase();

		// Database version
		boolean mVersion = comparePackageVersion();

		if (!mDataBaseExist || mVersion) {
			this.getReadableDatabase();
			this.close();
			try {
				// Copy the database from assests
				copyDataBase();
				Toast.makeText(mContext, mContext.getResources().getString(R.string.db_notify), Toast.LENGTH_LONG).show();
				Log.e(TAG, "createDatabase database created");
			}
			catch (IOException mIOException) {
				throw new Error("ErrorCopyingDataBase");
			}
		}
	}

	// Check that the database exists here: /data/data/your package/databases/Da
	// Name
	private boolean checkDataBase()
	{
		File dbFile = new File(DB_PATH + DB_NAME);
		// Log.v("dbFile", dbFile + "   "+ dbFile.exists());
		return dbFile.exists();
	}

	// Copy the database from assets
	private void copyDataBase() throws IOException
	{
		InputStream mInput = mContext.getAssets().open(DB_NAME);
		String outFileName = DB_PATH + DB_NAME;
		OutputStream mOutput = new FileOutputStream(outFileName);
		byte[] mBuffer = new byte[1024];
		int mLength;
		while ((mLength = mInput.read(mBuffer)) > 0) {
			mOutput.write(mBuffer, 0, mLength);
		}
		mOutput.flush();
		mOutput.close();
		mInput.close();
	}

	// Open the database, so we can query it
	public boolean openDataBase() throws SQLException
	{
		String mPath = DB_PATH + DB_NAME;
		// Log.v("mPath", mPath);
		mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
		// mDataBase = SQLiteDatabase.openDatabase(mPath, null,
		// SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		return mDataBase != null;
	}

	@Override
	public synchronized void close()
	{
		if (mDataBase != null)
			mDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase arg0)
	{
		// TODO Auto-generated method stub
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		// TODO Auto-generated method stub
	}
}
